import {
  ajaxFun
} from "../../../utils/ajax"
Page({


  data: {
    id: "", //商品id
    productInfo: {},
    productAttr: [], //商品规格数组
    swiperArry: [],
    list: [],
    show: false, //控制优惠劵弹出层
    active: 0,
    quanType: ["通用券", "优惠券", "品类券"],
    i: 0, //优惠券的索引
    quanList: [],
    show2: false, //商品规格 弹窗
    num: 1,
    count: 0, //购物车数量
    userCollect: false

  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    this.getGoodsdes(options.id); //商品信息
    this.getQuan() //获取优惠价列表---通用卷
    this.getGoodsNum() //获取加入购物车数量
  },
  async getGoodsdes(id) {
    let {
      productInfo,
      productAttr,
      userCollect
    } = await ajaxFun(`/product/detail/${id}`, "get", {
      type: "normal"
    })
    let swiperArry = JSON.parse(productInfo.sliderImage);
    let {
      list
    } = await ajaxFun("/product/good", "get")
    this.setData({
      productInfo,
      swiperArry,
      list,
      productAttr,
      userCollect
    })
  },
  async getGoodsNum() { //获取加入购物车数量
    let {
      count
    } = await ajaxFun("/cart/count", "get", {
      numType: true,
      type: "total"
    })
    this.setData({
      count
    })
  },
  showFun() {
    this.setData({
      show: true
    });

  },
  onClose() {
    this.setData({
      show: false,
      show2: false
    });
  },
  tabFun(e) { // tab切换效果 ---ajax

    this.setData({
      i: e.target.dataset.index
    }, () => {
      this.getQuan()
    })

  },
  async getQuan() { //获取优惠劵
    let {
      list
    } = await ajaxFun("/coupons", "get", {
      page: 1,
      limit: 999,
      productId: this.data.id,
      type: this.data.i + 1
    })
    this.setData({
      quanList: list
    })
  },
  showAttr() {
    this.setData({
      show2: true
    })
  },
  onChange(event) {
    console.log(event.detail);
    this.setData({
      num: event.detail
    })
  },
  async addCart() {
    let {
      cartId
    } = await ajaxFun("/cart/save", "post", {
      cartNum: this.data.num,
      isNew: false,
      productAttrUnique: this.data.productAttr[0].id,
      productId: this.data.id
    })
    if (cartId) {
      this.getGoodsNum() //获取加入购物车数量
      wx.showToast({
        title: '加入购物车成功',
      })
      this.setData({
        show2: false
      })
    }
  },
  goCart() {
    wx.switchTab({ //去购物车
      url: '/pages/cart/cart',
    })
  },
  async setOrder() { //生成订单号
    let {preOrderNo} = await ajaxFun("/order/pre/order", "post", {
      orderDetails: [{
        attrValueId: this.data.productAttr[0].id,//规格id
        productId: this.data.id,//商品id
        productNum: this.data.num//商品数量
      }],
      preOrderType: "buyNow"
    })
    wx.navigateTo({//去支付页面
      url: `/indexPackage/pages/payfor/payfor?preOrderNo=${preOrderNo}`,
    })
  }

})